/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        // if (!root)
        //     return {};
        // stack<TreeNode*> S;
        // S.push(root);
        // vector<vector<int>> ans;
        // vector<int> curLevel;
        // while (!S.empty()) {
        //     stack<TreeNode*> tmpS;
        //     while (!S.empty()) {
        //         TreeNode* tmpNode = S.top();
        //         S.pop();
        //         curLevel.push_back(tmpNode->val);
        //         if (tmpNode->left)
        //             tmpS.push(tmpNode->left);
        //         if (tmpNode->right)
        //             tmpS.push(tmpNode->right);
        //     }
        //     ans.push_back(curLevel);
        //     S = tmpS;
        // }
        // return ans;
        // 使用双栈很麻烦
        if (!root)
            return {};
        queue<TreeNode*> q;
        q.push(root);
        vector<vector<int>> ans;
        while (!q.empty()) {
            int size = q.size();
            vector<int> level;
            for (int i = 0; i < size; ++i) {
                TreeNode* node = q.front();
                q.pop();
                level.push_back(node->val);
                if (node->left)
                    q.push(node->left);
                if (node->right)
                    q.push(node->right);
            }
            ans.push_back(level);
        }
        return ans;
    }
};
